package com.kang.basicalgorithm.bubblesort;

import java.util.Arrays;

/**
 * @author xukang
 * @date 2021-10-22 15:23
 * 冒泡排序
 */
public class BubbleSort {
    public static void main(String[] args) {
//        int[] array = {2,1,43,34,454,56,75,453,44,43,4,543,6,57,56,7,34,34,24,345,54,756,99};
        int[] array = {5,9,7,4,1,3,2,8};
        for (int j = 0; j < array.length; j++) {
            System.out.println("第" + j + "轮");
            // 减去j  减少交换次数
            boolean ifSwap = false;
            for (int i = 0; i < array.length-1-j; i++) {
                System.out.println("比较次数"+i);
                if (array[i] > array[i + 1]) {
                    swap(array, i, i + 1);
                     ifSwap = true;
                }
            }
            System.out.println("排序后的数组"+Arrays.toString(array));
            if (!ifSwap) {
                break;
            }
        }
    }

    public static void swap(int[] array,int i,int j) {
        int t = array[i];
        array[i] = array[j];
        array[j] =t;

    }
}
